"""
This file is part of GSBEdit. For copyright and licensing information, please
see gsbedit.py in the GSBEdit base directory.
"""


import ConfigParser
import os.path


class ConfigFile:
    def __init__(self, filename=None):
        self.filename = filename
        
        self.data = ConfigParser.ConfigParser()
        if os.path.exists(filename):
            self.data.read(filename)
        else:
            self.create_sections()
        
        
    def get_filename(self):
        return self.filename


    def get_name(self):
        if self.has_value('config', 'uiname'):
            return self.get_value('config', 'uiname')
        elif self.has_value('config', 'guiname'):
            return self.get_value('config', 'guiname')
        else:
            print >> sys.stderr, "Config file %s has no friendly name" % self.filename
            return '??'
        
    def get_internal_name(self):
        return self.get_value('config', 'name')
        
        
    def write_to_file(self, filename=None):
        if filename == None:
            filename = self.get_filename()
        outfile = open(filename, 'w')
        self.data.write(outfile)
        outfile.close()
    
    
    def delete(self):
        os.remove(self.filename)

    def has_value(self, section, name):
        return self.data.has_option(section, name)
    
    def get_value(self, section, name):
        return self.data.get(section, name).replace('"', '')

    def set_value(self, section, name, value):
        if ' ' in value: value = '"%s"' % value
        self.data.set(section, name, value)
    
    def get_values(self, section):
        result = {}
        values = self.data.items(section)
        for (k,v) in values:
            result[k] = v.replace('"', '')
        return result

    def update_values(self, section, values):
        """
        Updates several values in one operation. Any values supplied as either
        an empty string or the value None are removed.
        """
        for key, value in values.iteritems():
            if value in [None, '']:
                self.data.remove_option(section, key)
            else:
                self.data.set(section, key, value)
